package com.gzc.just.play.last.war.sceneserver;

import com.gzc.just.play.last.war.sceneserver.battle.manager.EnhancedBattleSessionManager;
import com.gzc.just.play.last.war.sceneserver.config.SceneConfig;
import com.gzc.just.play.last.war.sceneserver.gs.GateServerInfo;
import com.gzc.just.play.last.war.sceneserver.gs.GateServerManager;
import com.gzc.just.play.last.war.common.handler.VirtualThreadServerFramework;
import com.gzc.just.play.last.war.common.net.NetUtils;
import com.gzc.just.play.last.war.protobuf.cs.cstoss.CSToSS;
import com.gzc.just.play.last.war.protobuf.ss.sstocs.SSToCS;
import com.google.protobuf.Message;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 场景服务器工作线程管理器
 * 重构版本：移除BattleLogicThreadActor，使用EnhancedBattleSessionManager管理虚拟线程战斗会话
 * 对应C++的CSSWorkThreadMgr类，负责管理场景服务器的线程池和战斗逻辑处理
 */
@Component
public class SceneWorkThreadManager {
    private static final Logger logger = LoggerFactory.getLogger(SceneWorkThreadManager.class);
    
    @Autowired
    private SceneConfig sceneConfig;
    
    @Autowired
    private EnhancedBattleSessionManager enhancedBattleSessionManager;
    
    @Autowired
    private GateServerManager gateServerManager;
    
    @Autowired(required = false)
    private VirtualThreadServerFramework virtualThreadServerFramework;
    
    @Autowired
    private com.gzc.just.play.last.war.sceneserver.service.BattleMessageRoutingService battleMessageRoutingService;
    
    @Value("${scene.server.id:1}")
    private int sceneServerId;
    
    @Value("${scene.server.thread.num:4}")
    private int threadNum;
    
    @Value("${scene.server.mini.battle.obj.num:100}")
    private int miniBattleObjNum;
    
    // 系统初始化时间
    private Instant initTime;
    
    // 统计信息
    private AtomicLong runCounts = new AtomicLong(0);
    private AtomicLong lastReport = new AtomicLong(0);
    
    // 配置参数
    private long npcMaxLifeTime = 60000; // NPC最大生存时间
    private long battleFinishProtectTimeSpan = 60000; // 战斗结束保护时间
    private int maxStatisMsgToShow = 5; // 最大显示统计消息数
    private long msgStaticsInterval = 60000; // 消息统计间隔
    private boolean enableStatics = true; // 是否启用统计
    
    @PostConstruct
    public void init() {
        logger.info("Initializing SceneWorkThreadManager with virtual thread battle sessions");
        
        initTime = Instant.now();
        
        // 初始化虚拟线程服务器框架
        if (virtualThreadServerFramework != null) {
            virtualThreadServerFramework.init();
            logger.info("VirtualThreadServerFramework initialized");
        }
        
        logger.info("SceneWorkThreadManager initialized successfully");
    }
    
    @PreDestroy
    public void destroy() {
        logger.info("Destroying SceneWorkThreadManager");
        
        // 清理所有战斗会话
        if (enhancedBattleSessionManager != null) {
            enhancedBattleSessionManager.clearAllBattles();
        }
        
        // 关闭虚拟线程服务器框架
        if (virtualThreadServerFramework != null) {
            virtualThreadServerFramework.shutdown();
        }
        
        logger.info("SceneWorkThreadManager destroyed");
    }
    
    /**
     * 处理来自GateServer的消息
     * 重构版本：使用BattleMessageRoutingService将消息路由到对应的处理组件
     */
    public void handleGSMessage(ChannelHandlerContext ctx, int messageId, byte[] messageData) {
        // 获取GateServer信息
        GateServerInfo gsInfo = gateServerManager.getGSInfoByChannelId(ctx.channel().id().asLongText());
        if (gsInfo == null) {
            logger.error("Cannot find GateServer info for channel: {}", ctx.channel().id());
            return;
        }
        
        // 使用消息路由服务处理消息
        boolean success = battleMessageRoutingService.routeGSMessage(ctx, messageId, messageData);
        if (!success) {
            logger.error("Failed to route GS message: messageId={}", messageId);
        }
    }
    
    /**
     * 处理来自CentralServer的消息
     * 重构版本：使用BattleMessageRoutingService将消息路由到对应的处理组件
     */
    public void handleCSMessage(int messageId, byte[] messageData) {
        // 使用消息路由服务处理消息
        boolean success = battleMessageRoutingService.routeCSMessage(messageId, messageData);
        if (!success) {
            logger.error("Failed to route CS message: messageId={}", messageId);
        }
    }
    
    /**
     * 检查与CentralServer的连接
     */
    @Scheduled(fixedDelay = 5000) // 每5秒检查一次
    public void checkCSConnect() {
        // 实现与CentralServer的心跳检查
        // 这里简化处理，实际应该发送心跳消息并等待响应
        runCounts.incrementAndGet();
        
        // 触发战斗会话管理器心跳
        if (enhancedBattleSessionManager != null) {
            enhancedBattleSessionManager.onHeartbeat();
        }
        
        // 可以在这里添加连接状态检查和重连逻辑
        if (runCounts.get() % 12 == 0) { // 每分钟记录一次
            logger.debug("CS connection check, run count: {}", runCounts.get());
        }
    }
    
    /**
     * 性能统计报告
     * 重构版本：使用EnhancedBattleSessionManager获取性能统计
     */
    @Scheduled(fixedDelay = 10000) // 每10秒报告一次
    public void profileReport() {
        if (!enableStatics) {
            return;
        }
        
        long currentTime = System.currentTimeMillis();
        long lastReportTime = lastReport.get();
        
        if (currentTime - lastReportTime >= msgStaticsInterval) {
            if (lastReport.compareAndSet(lastReportTime, currentTime)) {
                logger.info("Scene Server Performance Report:");
                logger.info("- Thread count: {} (virtual threads per battle)", "N/A");
                logger.info("- Scene server ID: {}", sceneServerId);
                
                // 从EnhancedBattleSessionManager获取性能统计
                if (enhancedBattleSessionManager != null) {
                    var stats = enhancedBattleSessionManager.getPerformanceStats();
                    logger.info("- Total battles: {}", stats.get("totalBattles"));
                    logger.info("- Active battles: {}", stats.get("activeBattles"));
                    logger.info("- Total players: {}", stats.get("totalPlayers"));
                    logger.info("- Total queue size: {}", stats.get("totalQueueSize"));
                }
            }
        }
    }
    
    /**
     * 发送消息到CentralServer
     */
    public void sendMsgToCS(Message message, int msgId) {
        try {
            // 通过GateServer转发到CentralServer
            gateServerManager.broadcastToAllGS(message.toByteArray(), msgId);
        } catch (Exception e) {
            logger.error("Failed to send message to CentralServer, msgId: {}", msgId, e);
        }
    }
    

    
    // Getter和Setter方法
    public int getSceneServerId() {
        return sceneServerId;
    }
    
    public int getThreadNum() {
        return threadNum;
    }
    
    public int getMiniBattleObjNum() {
        return miniBattleObjNum;
    }
    
    public long getNpcMaxLifeTime() {
        return npcMaxLifeTime;
    }
    
    public long getBattleFinishProtectTimeSpan() {
        return battleFinishProtectTimeSpan;
    }
    
    public Instant getInitTime() {
        return initTime;
    }
    
    public long getRunCounts() {
        return runCounts.get();
    }
    
    public EnhancedBattleSessionManager getEnhancedBattleSessionManager() {
        return enhancedBattleSessionManager;
    }
    
    /**
     * 处理用户断开连接
     */
    public void handleUserDisconnection(ChannelHandlerContext ctx) {
        battleMessageRoutingService.handleUserDisconnection(ctx);
    }
}